﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace LsoaClass.SystemMaintain
{
    public class SystemClass : LsDBClass
    {
        /// <summary>
        /// 根据参数名称获取参数值（系统配置）
        /// </summary>
        /// <param name="paramName">参数名称</param>
        /// <param name="setting">参数值</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string getConfigByName(string paramName, out string setting)
        {
            setting = "";
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand("select Setting from SystemConfig_T where ParamName = @ParamName");
                cmd.Parameters.AddWithValue("@ParamName", paramName);
                setting = Convert.ToString(cmd.ExecuteScalar());
                funResult.Code = 0;
                funResult.Msg = "获取系统配置成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "获取系统配置失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 获取系统帐号信息列表。
        /// </summary>
        /// <param name="pageSize">每页的记录数</param>
        /// <param name="currentPage">当前页码</param>
        /// <param name="pageCount">总页数</param>
        /// <param name="recCount">总记录数</param>
        /// <param name="ds">返回数据集</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountList(int pageSize, int currentPage, out int pageCount, out int recCount, out DataSet ds)
        {
            pageCount = 0;
            recCount = 0;
            ds = null;
            DBClass dbc = new DBClass();
            try
            {
                string strsql = "select * from SystemAccount_T";
                ds = dbc.getPageDataSet(pageSize, currentPage, strsql, out recCount, out pageCount);
                funResult.Code = 0;
                funResult.Msg = "获取系统帐号信息列表成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "获取系统帐号信息列表失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 获取系统帐号信息
        /// </summary>
        /// <param name="systemID">系统帐号</param>
        /// <param name="ds">返回数据集</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountInfo(string systemID, out DataSet ds)
        {
            ds = null;
            DBClass dbc = new DBClass();
            try
            {
                ds = dbc.getDataSetBySql("select * from SystemAccount_T where SystemID = '" + systemID + "'");
                funResult.Code = 0;
                funResult.Msg = "获取系统帐号信息成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "获取系统帐号信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 增加系统帐号信息
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="systemID">系统帐号</param>
        /// <param name="systemName">系统名称</param>
        /// <param name="systemPassword">系统密码</param>   
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountAdd(string operatorID, string systemID, string systemName, string systemPassword)
        {
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand(@"
                    declare @RetStr nvarchar(50), @Log nvarchar(50)
                    if not exists (select * from SystemAccount_T where SystemID = @SystemID)
                    begin
	                    insert into SystemAccount_T(SystemID, SystemName, SystemPassword) values(@SystemID, @SystemName, @SystemPassword)
                        set @Log = '增加系统帐号信息。（帐号：' + @SystemID + '）' 
                        exec RecordLog @OperatorID, @Log
	                    set @RetStr = '0|增加系统帐号信息成功。'
                    end else
	                    set @RetStr = '15120000|该系统帐号已经存在。'
                    select @RetStr");
                cmd.Parameters.AddWithValue("@SystemID", systemID);
                cmd.Parameters.AddWithValue("@SystemName", systemName);
                cmd.Parameters.AddWithValue("@SystemPassword", CommonFunc.sha1Encrypt(systemID + systemPassword));
                cmd.Parameters.AddWithValue("@OperatorID", operatorID);
                funResult.RetStr = Convert.ToString(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "增加系统帐号信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 修改系统帐号信息
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="systemID">系统帐号</param>
        /// <param name="systemName">系统名称</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountModify(string operatorID, string systemID, string systemName)
        { 
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand("update SystemAccount_T set SystemName = @SystemName where SystemID = @SystemID");
                cmd.Parameters.AddWithValue("@SystemName", systemName);
                cmd.Parameters.AddWithValue("@SystemID", systemID);
                cmd.ExecuteNonQuery();
                recordLog(operatorID, "修改系统帐号信息。（帐号：" + systemID + "）");
                funResult.Code = 0;
                funResult.Msg = "修改系统帐号信息成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "修改系统帐号信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 修改系统帐号密码
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="systemID">系统帐号</param>
        /// <param name="systemPassword">系统密码</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountSetPwd(string operatorID, string systemID, string systemPassword)
        {
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand("update SystemAccount_T set SystemPassword = @SystemPassword where SystemID = @SystemID");
                cmd.Parameters.AddWithValue("@SystemPassword", CommonFunc.sha1Encrypt(systemID + systemPassword));
                cmd.Parameters.AddWithValue("@SystemID", systemID);
                cmd.ExecuteNonQuery();
                recordLog(operatorID, "修改系统帐号密码。（帐号：" + systemID + "）");
                funResult.Code = 0;
                funResult.Msg = "修改系统帐号密码成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "修改系统帐号密码失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 启用/停用系统帐号
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="systemID">系统帐号</param>
        /// <param name="enabled">启用/停用</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountSetEnabled(string operatorID, string systemID, bool enabled)
        { 
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand("update SystemAccount_T set Enabled = @Enabled where SystemID = @SystemID");
                cmd.Parameters.AddWithValue("@Enabled", enabled);
                cmd.Parameters.AddWithValue("@SystemID", systemID);
                cmd.ExecuteNonQuery();
                if (enabled)
                    recordLog(operatorID, "启用系统帐号。（帐号：" + systemID + "）");
                else
                    recordLog(operatorID, "停用系统帐号。（帐号：" + systemID + "）");
                funResult.Code = 0;
                if (enabled)
                    funResult.Msg = "启用系统帐号成功。";
                else
                    funResult.Msg = "停用系统帐号成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                if (enabled)
                    funResult.Msg = "启用系统帐号失败。" + ex.Message;
                else
                    funResult.Msg = "停用系统帐号失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 删除系统帐号
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="systemIDStr">系统帐号串</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemAccountDelete(string operatorID, string systemIDStr)
        {
            DBClass dbc = new DBClass();
            try
            {
                dbc.executeSqlCommand("delete from SystemAccount_T where SystemID in ('" + systemIDStr.Replace(",", "','") + "')");
                recordLog(operatorID, "删除系统帐号信息。（帐号：" + systemIDStr + "）");
                funResult.Code = 0;
                funResult.Msg = "删除系统帐号信息成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "删除系统帐号信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="descript">描述说明</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string recordLog(string operatorID, string descript)
        {
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand("RecordLog");
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@OperatorID", operatorID);
                cmd.Parameters.AddWithValue("@Descript", descript);
                cmd.ExecuteNonQuery();
                funResult.Code = 0;
                funResult.Msg = "记录操作日志成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "记录操作日志失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 创建注册码
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="pwd">操作密码</param>
        /// <param name="systemName">系统名称</param>
        /// <param name="userLimit">用户数量</param>
        /// <param name="dateLimit">使用期限</param>
        /// <param name="systemNo">系统编号</param>
        /// <param name="bindBranchName">是否需要绑定本部名称</param>
        /// <param name="checkCode">注册码</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string createCheckCode(string operatorID, string pwd, string systemName, int userLimit, string dateLimit, string systemNo, out string checkCode)
        {
            checkCode = "";
            if (operatorID == "admin" && pwd == "admin@Lees.com")
            {
                checkCode = CommonFunc.desEncrypt(systemName + "|" + userLimit.ToString() + "|" + dateLimit + "|" + systemNo, CommonFunc.EncryptKey);
                recordLog(operatorID, "创建注册码。（系统名称：" + systemName + "，用户数量：" + userLimit.ToString() + "，使用期限：" + dateLimit + "，系统编号：" + systemNo + "）");
                funResult.Code = 0;
                funResult.Msg = "生成注册码成功。";
            }
            else
            {
                funResult.Code = 12120000;
                funResult.Msg = "没有权限生成注册码。";
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 注册系统。
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="checkCode">注册码</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string systemRegist(string operatorID, string checkCode)
        {
            if (operatorID == "admin")
            {
                DBClass dbc = new DBClass();
                try
                {
                    string systemname, userlimit, datelimit, systemno;
                    string[] checks = CommonFunc.desDecrypt(checkCode, CommonFunc.EncryptKey).Split('|');
                    systemname = checks[0];
                    userlimit = checks[1];
                    datelimit = checks[2];
                    systemno = checks[3];
                    SqlCommand cmd = dbc.getSqlCommand(@"
                        update SystemConfig_T set setting = @SystemName where ParamName = 'SYSTEM_NAME'
                        update SystemConfig_T set setting = @UserLimit where ParamName = 'USER_LIMIT'
                        update SystemConfig_T set setting = @DateLimit where ParamName = 'DATE_LIMIT'
                        update SystemConfig_T set setting = @SystemNo where ParamName = 'SYSTEM_NO'
                        update SystemConfig_T set setting = @CheckCode where ParamName = 'CHECK_CODE'");
                    cmd.Parameters.AddWithValue("@SystemName", systemname);
                    cmd.Parameters.AddWithValue("@UserLimit", userlimit);
                    cmd.Parameters.AddWithValue("@DateLimit", datelimit);
                    cmd.Parameters.AddWithValue("@SystemNo", systemno);
                    cmd.Parameters.AddWithValue("@CheckCode", checkCode);
                    cmd.ExecuteNonQuery();
                    recordLog(operatorID, "注册系统。（系统名称：" + systemname + "，用户数量：" + userlimit + "，使用期限：" + datelimit + "，系统编号：" + systemno + "）");
                    funResult.Code = 0;
                    funResult.Msg = "注册系统成功。";
                }
                catch (Exception ex)
                {
                    funResult.Code = 13120000;
                    funResult.Msg = "注册系统失败。" + ex.Message;
                }
                finally
                {
                    dbc.close();
                }
            }
            else
            {
                funResult.Code = 12120000;
                funResult.Msg = "没有权限注册系统。";
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 验证系统注册码
        /// </summary>
        /// <returns></returns>
        public static string checkSystemCode()
        {
            string checkcode, systemname, systemno, userlimit, datelimit;
            getConfigByName("CHECK_CODE", out checkcode);
            getConfigByName("SYSTEM_NAME", out systemname);
            getConfigByName("USER_LIMIT", out userlimit);
            getConfigByName("DATE_LIMIT", out datelimit);
            getConfigByName("SYSTEM_NO", out systemno);
            if (CommonFunc.desEncrypt(systemname + "|" + userlimit + "|" + datelimit + "|" + systemno, CommonFunc.EncryptKey) == checkcode)
            {
                TimeSpan diff = DateTime.Parse(datelimit) - DateTime.Now;
                double diffday = diff.TotalDays;
                if (diffday < 0)
                {
                    funResult.Code = 10120001;
                    funResult.Msg = "系统已过期，请尽快与管理员联系。";
                }
                else
                {
                    DBClass dbc = new DBClass();
                    try
                    {
                        SqlCommand cmd = dbc.getSqlCommand("select count(*) from User_T where UserState <> 1");
                        int usercount = Convert.ToInt32(cmd.ExecuteScalar().ToString());
                        if (usercount > Convert.ToInt32(userlimit))
                        {
                            funResult.Code = 10120002;
                            funResult.Msg = "系统人数上限已超过，请与管理员联系。";
                        }
                        else
                        {
                            if (diffday < 30)
                            {
                                funResult.Code = 10120003;
                                funResult.Msg = "系统的有效期至" + datelimit + "，请尽快与管理员联系。";
                            }
                            else
                            {
                                funResult.Code = 0;
                                funResult.Msg = "系统注册码验证通过。";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        funResult.Code = 13120000;
                        funResult.Msg = "系统注册码有误，请与管理员联系。" + ex.Message;
                    }
                    finally 
                    {
                        dbc.close();
                    }                    
                }
            }
            else
            {
                funResult.Code = 10120000;
                funResult.Msg = "系统注册码有误，请与管理员联系。";
            }
            return funResult.RetStr;
        }
    }
}
